<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 动态标题：根据页面类型显示不同标题 -->
    <h1 class="text-2xl font-bold mb-6">
      <span v-if="pageType === 'search' && searchKeyword">搜索结果: "{{ searchKeyword }}"</span>
      <span v-else-if="pageType === 'filter'">{{ filterTitle }}</span>
      <span v-else-if="pageType === 'section'">{{ sectionTitle }}</span>
      <span v-else>文章列表</span>
    </h1>

    <!-- 搜索表单：在搜索和筛选页面显示 -->
    <div v-if="pageType === 'search' || pageType === 'filter'" class="mb-8">
      <SearchBar />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <svg class="animate-spin h-8 w-8 text-[#C32A31]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    </div>

    <!-- 错误信息 -->
    <div v-else-if="error" class="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
      <div class="flex">
        <div class="flex-shrink-0">
          <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="ml-3">
          <p class="text-sm text-red-700">{{ error }}</p>
        </div>
      </div>
    </div>

    <!-- 文章列表：统一的文章显示格式 -->
    <div v-else-if="articles.length > 0" class="space-y-6">
      <div v-for="article in articles" :key="article.newsId" class="bg-white shadow overflow-hidden sm:rounded-lg hover:shadow-md transition-shadow duration-200">
        <div class="px-4 py-5 sm:px-6">
          <div class="flex justify-between items-start">
            <h3 class="text-lg leading-6 font-medium text-[#C32A31] flex-1">
              <router-link :to="`/news/${article.newsId}`" class="hover:underline">
                {{ article.title }}
              </router-link>
            </h3>
            <span class="text-sm text-gray-500 whitespace-nowrap ml-4">{{ formatDate(article.pubTime) }}</span>
          </div>

          <div class="flex items-center text-sm text-gray-500 mt-1 mb-3">
            <span class="mr-4">分类: {{ article.category }}</span>
            <span v-if="article.section" class="mr-4">部门: {{ article.section }}</span>
          </div>

          <p class="text-sm text-gray-700 line-clamp-3 mb-3">
            {{ getContentPreview(article) }}
          </p>

          <div class="flex items-center justify-between">
            <router-link :to="`/news/${article.newsId}`" class="inline-flex items-center text-[#C32A31] hover:text-[#991E29] text-sm font-medium">
              阅读全文
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </router-link>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div class="mt-6 flex flex-col sm:flex-row justify-center items-center gap-4">
        <div class="flex items-center text-sm text-gray-700">
          <span>共 {{ totalPages }} 页，当前第</span>
          <input
            v-model.number="pageInput"
            type="number"
            min="1"
            :max="totalPages"
            class="w-12 mx-2 px-2 py-1 border border-gray-300 rounded text-center focus:ring-[#C32A31] focus:border-[#C32A31]"
            @keyup.enter="goToPage"
          >
          <span>页</span>
        </div>
        
        <nav class="flex items-center gap-1">
          <button
            @click="changePage(1)"
            :disabled="currentPage <= 1"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage <= 1 ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            首页
          </button>
          <button
            @click="changePage(currentPage - 1)"
            :disabled="currentPage <= 1"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage <= 1 ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            上一页
          </button>
          <button
            @click="changePage(currentPage + 1)"
            :disabled="!hasMorePages"
            class="px-3 py-1 border rounded text-sm"
            :class="!hasMorePages ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            下一页
          </button>
          <button
            @click="changePage(totalPages)"
            :disabled="currentPage >= totalPages"
            class="px-3 py-1 border rounded text-sm"
            :class="currentPage >= totalPages ? 'border-gray-200 text-gray-400' : 'border-gray-300 text-gray-700 hover:bg-gray-50'"
          >
            尾页
          </button>
        </nav>
      </div>
    </div>

    <!-- 无结果提示：根据页面类型显示不同提示 -->
    <div v-else class="bg-white shadow overflow-hidden sm:rounded-lg p-6 text-center">
      <p class="text-gray-500">
        <span v-if="pageType === 'search' && searchKeyword">未找到与 "{{ searchKeyword }}" 相关的内容</span>
        <span v-else-if="pageType === 'filter'">未找到符合筛选条件的文章</span>
        <span v-else-if="pageType === 'section'">该学院/部门暂无文章</span>
        <span v-else>暂无文章</span>
      </p>
      <p class="mt-2 text-sm text-gray-500">
        <span v-if="pageType === 'search'">请尝试其他关键词或浏览我们的</span>
        <span v-else-if="pageType === 'filter'">请调整筛选条件或浏览我们的</span>
        <span v-else>请稍后再试，或浏览我校</span>
        <router-link :to="{ name: 'NewsList' }" class="text-[#C32A31] hover:underline">最新要闻</router-link>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import SearchBar from './index/SearchBar.vue';
import { homeApi, articleApi } from '../../utils/api';

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(true);
const error = ref(null);
const articles = ref([]); // 统一使用articles，支持搜索和section
const currentPage = ref(1);
const pageSize = ref(10);
const totalResults = ref(0);
const totalPages = ref(1);
const searchKeyword = ref('');
const selectedCategory = ref(''); // 选中的分类
const selectedSection = ref(''); // 选中的学院
const sectionName = ref(''); // 当前section名称（用于兼容旧的section路由）
const pageType = ref('search'); // 页面类型：'search' | 'section' | 'filter'
const pageInput = ref(1);

// 监听当前页码变化
watch(currentPage, (newVal) => {
  pageInput.value = newVal;
});

// 跳转到指定页码
const goToPage = () => {
  if (!pageInput.value || pageInput.value < 1) {
    pageInput.value = 1;
  } else if (pageInput.value > totalPages.value) {
    pageInput.value = totalPages.value;
  }
  changePage(pageInput.value);
};

// 计算属性
const hasMorePages = computed(() => {
  return currentPage.value < totalPages.value;
});

// section页面标题
const sectionTitle = computed(() => {
  return sectionName.value ? `${sectionName.value}文章列表` : '文章列表';
});

// 筛选页面标题
const filterTitle = computed(() => {
  const parts = [];
  if (selectedCategory.value) {
    parts.push(`分类: ${selectedCategory.value}`);
  }
  if (selectedSection.value) {
    parts.push(`学院: ${selectedSection.value}`);
  }
  if (searchKeyword.value) {
    parts.push(`关键词: ${searchKeyword.value}`);
  }

  if (parts.length > 0) {
    return `筛选结果 (${parts.join(' | ')})`;
  }
  return '筛选结果';
});

// 获取文章内容预览
const getContentPreview = (article) => {
  if (article.contentText) {
    return article.contentText.length > 200
      ? article.contentText.substring(0, 200) + '...'
      : article.contentText;
  }
  if (article.contentPreview) {
    return article.contentPreview;
  }
  return '无内容摘要';
};

// 处理分页数据的通用函数
const handlePaginationData = (result) => {
  // 检查响应是否为空或非对象
  if (!result || typeof result !== 'object') {
    console.error('Invalid response format:', result);
    return false;
  }

  // 情况1: 直接返回分页对象 {list: [...], total: number, pageNum: number, pageSize: number, pages: number}
  if (result.list && Array.isArray(result.list)) {
    articles.value = result.list;
    totalResults.value = result.total || 0;
    totalPages.value = result.pages || 1;
    currentPage.value = result.pageNum || currentPage.value;
    return true;
  }

  // 情况2: 标准响应格式 {code: 200, data: {...}}
  if (result.code !== undefined) {
    if (result.code !== 200) {
      error.value = result.msg || '请求失败';
      return false;
    }

    // 处理标准响应中的数据
    if (result.data && typeof result.data === 'object') {
      // 如果data是分页对象格式
      if (result.data.list) {
        articles.value = result.data.list || [];
        totalResults.value = result.data.total || 0;
        totalPages.value = result.data.pages || 1;
        currentPage.value = result.data.pageNum || currentPage.value;
      } else if (Array.isArray(result.data)) {
        // 如果data是数组
        articles.value = result.data;
      } else {
        // 其他对象格式
        articles.value = [];
      }
      return true;
    } else if (Array.isArray(result.data)) {
      // 直接返回数组
      articles.value = result.data;
      return true;
    }
  }

  // 情况3: 直接返回数组
  if (Array.isArray(result)) {
    articles.value = result;
    return true;
  }

  // 情况4: 未知格式
  console.warn('Unexpected response format:', result);
  articles.value = [];
  return false;
};

// 综合搜索文章（支持多条件筛选）
const searchArticles = async () => {
  loading.value = true;
  error.value = null;

  try {
    let result;

    // 检查是否有任何筛选条件
    const hasKeyword = searchKeyword.value && searchKeyword.value.trim();
    const hasCategory = selectedCategory.value && selectedCategory.value.trim();
    const hasSection = selectedSection.value && selectedSection.value.trim();

    if (!hasKeyword && !hasCategory && !hasSection) {
      // 没有任何筛选条件，获取最新文章
      result = await articleApi.getArticleList({ page: currentPage.value, limit: pageSize.value });
    } else {
      // 使用新的多条件搜索API
      result = await articleApi.searchWithMultipleConditions({
        keyword: hasKeyword ? searchKeyword.value.trim() : undefined,
        category: hasCategory ? selectedCategory.value.trim() : undefined,
        section: hasSection ? selectedSection.value.trim() : undefined,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });

      console.log('多条件搜索参数:', {
        keyword: hasKeyword ? searchKeyword.value.trim() : undefined,
        category: hasCategory ? selectedCategory.value.trim() : undefined,
        section: hasSection ? selectedSection.value.trim() : undefined,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
    }

    handlePaginationData(result);
  } catch (err) {
    console.error('Error searching articles:', err);
    error.value = '搜索失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 获取section文章列表
const fetchSectionArticles = async () => {
  if (!sectionName.value) return;

  loading.value = true;
  error.value = null;

  try {
    const response = await articleApi.getArticlesBySection(
      sectionName.value,
      currentPage.value,
      pageSize.value
    );

    handlePaginationData(response);
  } catch (err) {
    console.error('获取section文章列表请求错误:', err);
    error.value = '获取文章列表失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page) => {
  // 验证页码范围
  if (page < 1) return;
  if (page > totalPages.value) return;

  currentPage.value = page;

  // 更新URL参数，使用replace避免在浏览器历史中创建新条目
  router.replace({
    query: {
      ...route.query,
      page
    }
  });

  // 根据页面类型执行相应的数据获取
  if (pageType.value === 'search' || pageType.value === 'filter') {
    searchArticles();
  } else if (pageType.value === 'section') {
    fetchSectionArticles();
  }

  // 平滑滚动回页面顶部
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';

  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// 初始化页面数据
const initializePage = () => {
  const keyword = route.query.keyword;
  const category = route.query.category;
  const section = route.query.section;
  const sectionParam = route.params.section; // 兼容旧的section路由
  const page = parseInt(route.query.page) || 1;

  // 重置状态
  articles.value = [];
  error.value = null;
  currentPage.value = page;

  // 更新筛选条件
  searchKeyword.value = keyword || '';
  selectedCategory.value = category || '';
  selectedSection.value = section || '';

  // 判断页面类型和执行相应的数据获取
  if (sectionParam) {
    // 兼容旧的section路由模式
    pageType.value = 'section';
    sectionName.value = sectionParam;
    fetchSectionArticles();
  } else if (keyword || category || section) {
    // 新的筛选模式
    if (keyword && !category && !section) {
      pageType.value = 'search';
    } else {
      pageType.value = 'filter';
    }
    searchArticles();
  } else {
    // 无参数，显示空状态
    pageType.value = 'search';
    loading.value = false;
  }
};

// 监听路由参数变化
watch(() => [route.query, route.params], () => {
  initializePage();
}, { immediate: false, deep: true });

// 页面加载时初始化
onMounted(() => {
  initializePage();
});
</script>

<style scoped>
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
